package com.roseski.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import com.roseski.service.RoseskiOrderService;
import com.roseski.util.DateTimeUtil;
import com.roseski.wechatutil.MyConfig;
import com.roseski.wechatutil.WXPayConstants.SignType;
import com.roseski.wechatutil.WXPayUtil;

@Controller
@RequestMapping("order/wechat")
public class WechatController {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Value("${key}")
	private String key;
	@Autowired
	MyConfig myConfig;
	@Autowired
	RoseskiOrderService roseskiOrderService;
	
	/**
     * 接收支付通知
	 * @throws Exception 
     */
	@RequestMapping("/notify")
    //@ResponseBody
    public void notify(HttpServletRequest request, HttpServletResponse response) throws Exception{
    	
    	response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
        String notifyData = "";
        try {
            ServletInputStream in = request.getInputStream();
            notifyData = inputStream2String(in);
            logger.info("weixin pay notify msg:{}",notifyData);
            //WXPay wxpay = new WXPay(myConfig);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyData);  // 转换成map
            //if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
            if(WXPayUtil.isSignatureValid(notifyMap, key, SignType.HMACSHA256)) {
                // 签名正确，进行处理。注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
            	if("SUCCESS".equals(notifyMap.get("result_code"))
    					&&"SUCCESS".equals(notifyMap.get("return_code"))){
            		String payOrderNo = notifyMap.get("out_trade_no");
            		String transactionId = notifyMap.get("transaction_id");
            		String timeEnd = notifyMap.get("time_end");
            		Date date = new Date();
            		if(!StringUtils.isEmpty(timeEnd)) {
            			date = DateTimeUtil.formatToDate(timeEnd, "yyyyMMddHHmmss");
            		}
    	        	roseskiOrderService.updateSuccessStatus(payOrderNo, transactionId, date);
    	        	
    	        	response.getWriter().write(setXML("SUCCESS", "OK"));
            	}
            }else {
            	logger.info(" weixin pay notify handle fail , 签名错误");
            	response.getWriter().write(setXML("FAIL", "FAIL"));
            }
        } catch (IOException e) {
        	logger.error(e.getMessage(), e);
            response.getWriter().write(setXML("FAIL", ""));
        	return;
        }
        
    }
    
    private String inputStream2String(InputStream in) throws UnsupportedEncodingException, IOException{
        if(in == null)
            return "";

        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1;) {
            out.append(new String(b, 0, n, "UTF-8"));
        }
        return out.toString();
    }
      
     /**
	 * <pre>
	 * 返回给微信的参数
	 * </pre>
	 * @param return_code
	 * @param return_msg
	 * @return
	 */
	public static String setXML(String return_code, String return_msg)
	{
		return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg
				+ "]]></return_msg></xml>";
	}

}
